package lws.com.liwushuo.view.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import lws.com.liwushuo.R;
import lws.com.liwushuo.adapter.fenlei.DanpinDetailsRecyclerviewAdapter;
import lws.com.liwushuo.bean.fenlei.DanpinDetailsBean;
import lws.com.liwushuo.server.fenlei.FenleiService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class DetailsDanpinActivity extends AppCompatActivity implements View.OnClickListener, Callback<DanpinDetailsBean>, PtrHandler {

    private PtrClassicFrameLayout ptr;
    private RecyclerView recyclerView;
    private ImageView back;
    private ImageView sort;
    private DanpinDetailsRecyclerviewAdapter danpinDetailsRecyclerviewAdapter;
    private int id;
    private GridLayoutManager gridLayoutManager;

    //与刷新有关
    private boolean isRefreshingNow;
//    private boolean isCanRefreshing;
    private boolean isReallyComplete;
    private ImageView box;
    private ImageView aixin;
//    private AnimationSet aixin_animation;
    private Animation aixin_animation;
    private Animation aixin_animation_close;
    private View ptr_header;

    private static final int START_REFRESH = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START_REFRESH:
                    fenleiService.getDanpinDetailsBean(id, 20, 0).enqueue(DetailsDanpinActivity.this);

                    break;
            }
        }
    };
    private FenleiService fenleiService;
    private AnimationDrawable animationBackground;
    private AnimationSet animationSet;
    private String name;
    private TextView tv_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details__danpin_);

        Intent intent = getIntent();
        id = intent.getIntExtra("id", -1);
        name = intent.getStringExtra("name");

        tv_name = ((TextView) findViewById(R.id.tv_danpin_details_title));
        tv_name.setText(name);
        ptr = ((PtrClassicFrameLayout) findViewById(R.id.ptr_danpin_details));
        recyclerView = ((RecyclerView) findViewById(R.id.rv_danpin_details));
        gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);

        danpinDetailsRecyclerviewAdapter = new DanpinDetailsRecyclerviewAdapter(this, new ArrayList<DanpinDetailsBean.DataBean.ItemsBean>());

        back = ((ImageView) findViewById(R.id.iv_danpin_details_back));
        sort = ((ImageView) findViewById(R.id.iv_danpin_details_sort));
        back.setOnClickListener(this);

        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://api.liwushuo.com").addConverterFactory(GsonConverterFactory.create()).build();
        fenleiService = retrofit.create(FenleiService.class);
        fenleiService.getDanpinDetailsBean(id, 20, 0).enqueue(this);

        //与刷新有关
        ptr_header = LayoutInflater.from(this).inflate(R.layout.danpin_details_ptr_header, null);
        box = ((ImageView) ptr_header.findViewById(R.id.iv_ptr_header_box));
        aixin = ((ImageView) ptr_header.findViewById(R.id.iv_ptr_header_aixin));

        aixin_animation = AnimationUtils.loadAnimation(this, R.anim.danpin_details_ptr_header_aixin);
        aixin_animation_close = AnimationUtils.loadAnimation(this, R.anim.danpin_details_ptr_header_aixin_close);
        aixin_animation.setRepeatCount(0);
        aixin_animation.setFillAfter(true);

//        //创建动画集
//        aixin_animation = new AnimationSet(true);
//        //创建渐变动画
//        AlphaAnimation alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
//        alphaAnimation.setDuration(200);
//        //创建位移动画
//        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1.4F, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1.4f);
//        translateAnimation.setDuration(200);
//        //将动画加到集合中
//        aixin_animation.addAnimation(alphaAnimation);
//        aixin_animation.addAnimation(translateAnimation);

        aixin_animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                box.setBackgroundResource(R.drawable.danpin_details_ptr_header_box_close);
//                animationBackground = ((AnimationDrawable) box.getBackground());
//                animationBackground.start();
//                aixin.setVisibility(View.INVISIBLE);
                aixin.startAnimation(aixin_animation_close);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


//        box.setBackgroundResource(R.drawable.danpin_details_ptr_header_box_open);

        setPtr();//设置与ptr相关的内容

    }

    public void startAnimation() {

        box.setBackgroundResource(R.drawable.danpin_details_ptr_header_box_open);
        animationBackground = ((AnimationDrawable) box.getBackground());
        animationBackground.start();
//        int duration = 0;
//        for (int i = 0; i < animationBackground.getNumberOfFrames(); i++) {
//            duration += animationBackground.getDuration(i);
//        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                //此处调用第二个动画播放方法
                Log.e("自定义标签", "类DetailsDanpinActivity中的方法run: ");
//                aixin.setVisibility(View.VISIBLE);
                aixin.startAnimation(aixin_animation);
//                aixin.clearAnimation();
            }
        }, 1000);
    }

    public void setPtr() {
        ptr.setResistance(1.7f);
        ptr.setRatioOfHeaderHeightToRefresh(1.2f);
        ptr.setDurationToClose(200);
        ptr.setDurationToCloseHeader(1000);
        ptr.setPullToRefresh(false);
        ptr.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                isRefreshingNow = false;
                aixin.setVisibility(View.INVISIBLE);
                box.setBackgroundResource(R.drawable.danpin_details_ptr_header_box_open);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                int offsetToRefresh = ptrIndicator.getOffsetToRefresh();//刷新需要滑动的偏移量
                int currentPosY = ptrIndicator.getCurrentPosY();
                //如果手指已经松开并且当前的header的位置到达了刷新需要滑动的偏移量的位置，
                //就开始执行动画,并且进行刷新
                Log.e("自定义标签", "isUnderTouch:  " + isUnderTouch + "  offsetToRefresh:  " + offsetToRefresh + "  currentPosY:  " + currentPosY + "  isReallyComplete  " + isReallyComplete);
                if (!isUnderTouch && Math.abs(offsetToRefresh - currentPosY) < 2 && isReallyComplete) {
                    Log.e("自定义标签", "类DetailsDanpinActivity中的方法onUIPositionChange: 开始刷新00000");
//                    AnimationDrawable animationDrawable = (AnimationDrawable) box.getBackground();
//                    animationDrawable.start();
//                    aixin.startAnimation(aixin_animation);
                    isRefreshingNow = true;
                    isReallyComplete = false;
                }
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                Log.e("自定义标签", "类DetailsDanpinActivity中的方法onUIRefreshBegin: 开始刷新111111");
                startAnimation();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
//                isRefreshingNow = false;
//                aixin.setAlpha(0f);
//                aixin.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onUIReset(PtrFrameLayout frame) {
//                isRefreshingNow = false;
//                aixin.setAlpha(0f);
                box.setBackgroundResource(0);
//                aixin.setVisibility(View.INVISIBLE);
//                box.setBackgroundResource(R.drawable.danpin_details_ptr_header_box_open);
            }
        });
        ptr.setHeaderView(ptr_header);
        ptr.setPtrHandler(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_danpin_details_back:
                finish();
                break;
            case R.id.iv_danpin_details_sort:

                break;
        }
    }

    //会被时刻监听
    //检查是否可以执行下来刷新，比如列表为空或者列表第一项在最上面时。
    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {

        //判断recyclerview是否滑动到了最上面
        if (gridLayoutManager.findViewByPosition(gridLayoutManager.findFirstVisibleItemPosition()).getTop() == 0
                && gridLayoutManager.findFirstVisibleItemPosition() == 0) {
//            Log.e("自定义标签", "类DetailsDanpinActivity中的方法checkCanDoRefresh: true");
            return true;
        }
//        Log.e("自定义标签", "类DetailsDanpinActivity中的方法checkCanDoRefresh: false");
        return false;
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        handler.sendEmptyMessageDelayed(0, 3000);
    }

    @Override
    public void onResponse(Call<DanpinDetailsBean> call, Response<DanpinDetailsBean> response) {
        DanpinDetailsBean body = response.body();

        danpinDetailsRecyclerviewAdapter.addAll(body.getData().getItems());
        recyclerView.setAdapter(danpinDetailsRecyclerviewAdapter);
        //将刷新动画回复原状
        ptr.refreshComplete();  //刷新完成，view返回到原状
        isReallyComplete = true;
//        Log.e("自定义标签", "类DetailsDanpinActivity中的方法onResponse: ");
    }

    @Override
    public void onFailure(Call<DanpinDetailsBean> call, Throwable t) {

    }
}
